package com.bsoft.gol.hbs.service.impl.announcement;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hbs.dao.AnnouncementDAO;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.Dictionary;
import ctd.dictionary.controller.DictionaryController;
import ctd.mvc.upload.FileMetaEntity;
import ctd.mvc.upload.FileRegistry;
import ctd.mvc.upload.exception.FileRegistryException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.base.DoctorOrgs;
import hcn.base.Notification;
import hcn.base.announcement.DocAnnouncement;
import hcn.base.notification.event.NotificationEvent;
import hcn.common.Constants;
import hcn.util.CommonUtils;
import org.atag.dao.model.SimplePageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import pcn.bean.announcement.QueryAnnouncementListQo;
import pcn.service.announcement.AnnouncementService;
import pcn.vo.announcement.GetAnnouncementDetailVo;
import service.rpc.DoctorInfoServiceIntf;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author impel
 * @Date 2020/11/23 16:52
 * @Description: 院内公告
 * @Version 1.0
 */
@SsdevService("announcement")
public class AnnouncementServiceImpl implements AnnouncementService {
    private final Logger logger = LoggerFactory.getLogger(AnnouncementServiceImpl.class);

    @Autowired
    private AnnouncementDAO announcementDAO;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoService;
    @Autowired
    private FileRegistry fileRegistry;
    @Value("${net_image_url}")
    private String netServiceUrl;

    /**
     * 新增
     *
     * @param docAnnouncement
     */
    @Override
    @RpcService
    public void saveAnnouncement(DocAnnouncement docAnnouncement) {
        //若是租户级，给租户级的字段赋值
        List<Map<String, Object>> list = null;
        if ("1".equals(docAnnouncement.getAnnouncementType())) {
            docAnnouncement.setTenantId(UserRoleToken.getCurrentTenantId());
            docAnnouncement.setTenantName(docAnnouncement.getOrgName());
            try {
                list = doctorInfoService.queryUserIdList("", docAnnouncement.getOrgId());
            } catch (ControllerException e) {
                e.printStackTrace();
            }
        }else {
            try {
                list = doctorInfoService.queryUserIdList(docAnnouncement.getOrgId(), "");
            } catch (ControllerException e) {
                e.printStackTrace();
            }
        }
        
        logger.info("list={}", JSONObject.toJSONString(list));


        if (CommonUtils.isNotEmpty(docAnnouncement.getAnnouncementId())) {
            //查询老记录
            DocAnnouncement announcement = announcementDAO.get(docAnnouncement.getAnnouncementId());
            if (null != announcement) {
                //创建时间和创建人赋值
                docAnnouncement.setCreateTime(announcement.getCreateTime());
                docAnnouncement.setCreateUserId(announcement.getCreateUserId());
                docAnnouncement.setModifyTime(new Date());
                docAnnouncement.setModifyUserId(UserRoleToken.getCurrent().getUserId());
                docAnnouncement.setPublishTime(announcement.getPublishTime());
                //更新

                DocAnnouncement update = announcementDAO.update(docAnnouncement);
                if (CommonUtils.isNotEmpty(list)){
                    for (Map<String, Object> map : list) {
                        String userId = String.valueOf(map.get("userId"));
                        Notification notification = new Notification();
                        notification.setUserId(userId);
                        notification.setNotificationType(NotificationEvent.NotificateType.announcement.getGroup());
                        notification.setBusinessType(NotificationEvent.NotificateType.announcement.getTypeCode());
                        notification.setRoleId(NotificationEvent.NotificateType.announcement.getRoleId());
                        notification.setContent("你有一条院内公告请尽快查看");
                        notification.setTitle("你有一条院内公告请尽快查看");
                        notification.setStatus("0");
                        notification.setOperationable("0");
                        notification.setPushFlag("1");
                        notification.setSendTime(new Date());
                        if (CommonUtils.isNotEmpty(map.get("tenantId"))){
                            notification.setTenantId(String.valueOf(map.get("tenantId")));
                        }else {
                            notification.setTenantId(UserRoleToken.getCurrentTenantId());
                        }
                        if (CommonUtils.isNotEmpty(docAnnouncement)){
                            String notificationId = "{"+"\"announcementId\""+":\""+update.getAnnouncementId()+"\"}";
                            notification.setExtras(notificationId);
                        }
                        doctorInfoService.saveNotifications(notification);
                    }
                }
            }
        } else {
            //新增
            docAnnouncement.setAnnouncementId(UUID.randomUUID().toString());
            docAnnouncement.setTenantId(UserRoleToken.getCurrentTenantId());
            docAnnouncement.setDeleteFlag("0");
            docAnnouncement.setCreateTime(new Date());
            docAnnouncement.setPublishTime(new Date());
            if (CommonUtils.isNotEmpty(list)){
                for (Map<String, Object> map : list) {
                    String userId = String.valueOf(map.get("userId"));
                    Notification notification = new Notification();
                    notification.setUserId(userId);
                    notification.setNotificationType(NotificationEvent.NotificateType.announcement.getGroup());
                    notification.setBusinessType(NotificationEvent.NotificateType.announcement.getTypeCode());
                    notification.setRoleId(NotificationEvent.NotificateType.announcement.getRoleId());
                    notification.setContent("你有一条院内公告请尽快查看");
                    notification.setTitle("你有一条院内公告请尽快查看");
                    notification.setStatus("0");
                    notification.setOperationable("0");
                    notification.setPushFlag("1");
                    notification.setSendTime(new Date());
                    if (CommonUtils.isNotEmpty(map.get("tenantId"))){
                        notification.setTenantId(String.valueOf(map.get("tenantId")));
                    }else {
                        notification.setTenantId(UserRoleToken.getCurrentTenantId());
                    }
                    if (CommonUtils.isNotEmpty(docAnnouncement)){
                        String notificationId = "{"+"\"announcementId\""+":\""+docAnnouncement.getAnnouncementId()+"\"}";
                        notification.setExtras(notificationId);
                    }
                    doctorInfoService.saveNotifications(notification);
                }
            }
            announcementDAO.save(docAnnouncement);

        }
    }

    /**
     * 删除
     *
     * @param docAnnouncement
     */
    @Override
    @RpcService
    public void deleteAnnouncement(DocAnnouncement docAnnouncement) {

        if (CommonUtils.isNotEmpty(docAnnouncement.getAnnouncementId())) {
            DocAnnouncement docAnnouncement_new = announcementDAO.get(docAnnouncement.getAnnouncementId());
            docAnnouncement_new.setDeleteFlag("1");
            docAnnouncement_new.setDeleteTime(new Date());
            announcementDAO.update(docAnnouncement_new);
        }
    }

    /**
     * @description: 查询院内公告列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/23 22:30
     * @param: qo
     * @return: pcn.vo.announcement.GetAnnouncementDetailVo
     */
    @RpcService
    public SimplePageInfo<DocAnnouncement> queryAnnouncementList(QueryAnnouncementListQo qo) {
        try {
            if (CommonUtils.isNotEmpty(qo.getDoctorId())) {
                //机构id过滤
                List<String> orgIdList = new ArrayList<>();
                //租户id过滤
                List<String> tenantIdList = new ArrayList<>();

                //查询医生所在执业点列表
                List<DoctorOrgs> doctorOrgs = null;
                try {
                    doctorOrgs = doctorInfoService.queryOrgDoctorsByDoctorId(qo.getDoctorId());
                } catch (ControllerException e) {
                    e.printStackTrace();
                }
                if (CommonUtils.isNotEmpty(doctorOrgs)) {
                    for (DoctorOrgs orgDoctor : doctorOrgs) {
                        orgIdList.add(orgDoctor.getOrgId());
                        tenantIdList.add(orgDoctor.getTenantId());
                    }
                    qo.setOrgIdList(orgIdList);
                    qo.setTenantIdList(tenantIdList);
                }
            }

            SimplePageInfo<DocAnnouncement> docAnnouncementSimplePageInfo = announcementDAO.queryAnnouncementList(qo);
            if(null != docAnnouncementSimplePageInfo && CommonUtils.isNotEmpty(docAnnouncementSimplePageInfo.getList())){
                Dictionary dictionary = DictionaryController.instance().get("sys.tet.tenant");
                for (DocAnnouncement docAnnouncement : docAnnouncementSimplePageInfo.getList()) {
                    if(Constants.ONE_STRING.equals(docAnnouncement.getAnnouncementType())){
                        if(null != dictionary){
                            String text = dictionary.getText(docAnnouncement.getOrgId());
                            docAnnouncement.setOrgName(text);
                        }
                    }
                }
            }

            return docAnnouncementSimplePageInfo;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询院内公告失败");
        }
        return null;
    }


    /**
     * @description: 查询院内公告详情
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/23 23:51
     * @param: qo
     * @return: pcn.vo.announcement.GetAnnouncementDetailVo
     */
    @Override
    @RpcService
    public GetAnnouncementDetailVo getAnnouncementDetail(QueryAnnouncementListQo qo) throws ControllerException {
        GetAnnouncementDetailVo announcementDetailVo = new GetAnnouncementDetailVo();
        GetAnnouncementDetailVo.InnerFile innerFile = new GetAnnouncementDetailVo.InnerFile();
        if (CommonUtils.isEmpty(qo.getAnnouncementId())) {
            throw new ControllerException("院内公告记录标识不能为空");
        }
        DocAnnouncement docAnnouncement = announcementDAO.get(qo.getAnnouncementId());
        if (null == docAnnouncement) {
            throw new ControllerException("院内公告记录不存在");
        }

        ctd.util.BeanUtils.copy(docAnnouncement, announcementDetailVo);
        //返回文件信息,文件名称、文件类型、文件大小、文件下载地址
        if (CommonUtils.isNotEmpty(docAnnouncement.getAttachFileId())) {
            String[] AttachFileIds = docAnnouncement.getAttachFileId().split("\\,");
            List<FileMetaEntity> userFileMetaRecords = new ArrayList<>();

            for (String attachFileId : AttachFileIds) {
                try {
                    FileMetaEntity metaEntity = fileRegistry.load(attachFileId);
                    if(null != metaEntity){
                        userFileMetaRecords.add(metaEntity);
                    }
                } catch (FileRegistryException e) {
                    e.printStackTrace();
                }
            }

            if (CommonUtils.isNotEmpty(userFileMetaRecords)) {
                List<GetAnnouncementDetailVo.InnerFile> innerFiles = new ArrayList<>();
                for (FileMetaEntity userFileMetaRecord : userFileMetaRecords) {
                    innerFile = new GetAnnouncementDetailVo.InnerFile();
                    innerFile.setFileName(userFileMetaRecord.getFileName());
                    String sizeString = "";
                    BigDecimal size = new BigDecimal(userFileMetaRecord.getFileSize());
                    if (size.doubleValue() < 1024) {
                        sizeString = size.doubleValue() + "B";
                    } else if (size.doubleValue() >= 1024 && size.doubleValue() < 1024 * 1024) {
                        size = size.divide(new BigDecimal(1024), 2, BigDecimal.ROUND_UP);
                        sizeString = size.doubleValue() + "KB";
                    } else if (size.doubleValue() >= 1024 * 1024 && size.doubleValue() < 1024 * 1024 * 1024) {
                        size = size.divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_UP);
                        sizeString = size.doubleValue() + "MB";
                    }
                    innerFile.setFileSize(sizeString);
                    innerFile.setFileType(userFileMetaRecord.getContentType());
                    innerFile.setFileUrl(netServiceUrl + userFileMetaRecord.getFileId());
                    innerFile.setFileId(userFileMetaRecord.getFileId());
                    innerFiles.add(innerFile);
                }
                announcementDetailVo.setFileList(innerFiles);
            }
        }

        return announcementDetailVo;
    }

    ;


    /**
     * @description: 修改院内公告滚动状态
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/24 10:24
     * @param: qo
     * @return: void
     */
    @Override
    @RpcService
    public void updateAnnouncementStatus(DocAnnouncement qo) throws ControllerException {
        if (CommonUtils.isEmpty(qo.getAnnouncementId())) {
            throw new ControllerException("院内公告记录标识不能为空");
        }

        DocAnnouncement docAnnouncement = announcementDAO.get(qo.getAnnouncementId());
        if (null == docAnnouncement) {
            throw new ControllerException("院内公告记录不存在");
        }

        announcementDAO.updateDocAnnouncement(qo.getAnnouncementId(), qo.getAnnouncementStatus());
    }

}